
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DB.*;
import POJO.*;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Sibrand
 */
public class comments extends HttpServlet {

    private CommentManager db = new CommentManager(DBInfo.getConnection());
    private ContentManager db2 = new ContentManager(DBInfo.getConnection());
    private ContentContainerManager db3 = new ContentContainerManager(DBInfo.getConnection());
    private int contentID,  containerID,  commentID;
    private String user;
    private boolean ownerOfContainer;
    private boolean loggedIn;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servl
     * 
     * et request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String output = "";
        try {
            HttpSession sess = request.getSession();
            if ((request.getMethod().equals("POST") || request.getMethod().equals("post")) && request.getParameter("contentid") != null && sess.getAttribute("user") != null) {

                contentID = Integer.parseInt(request.getParameter("contentid"));
                containerID = db2.getContainerID(contentID);
                user = ((User) sess.getAttribute("user")).username;
                ownerOfContainer = db3.containerIsOwnedByUser(containerID, user);
                loggedIn = user != null;
                commentID = request.getParameter("commentid") == null ? -2 : Integer.parseInt(request.getParameter("commentid"));

                if (request.getParameter("content") != null) {
                    if (request.getParameter("text") != null && request.getParameter("commentid") != null && request.getParameter("containerid") != null) {
                        changeComment(user, commentID, contentID, containerID, request.getParameter("text").toString());
                    }

                    if (request.getParameter("commentid") != null && request.getParameter("containerid") != null && request.getParameter("del") != null) {
                        deleteComment(user, commentID, contentID, containerID);
                    }

                    if (request.getParameter("containerid") != null && request.getParameter("text") != null && request.getParameter("add") != null) {
                        addComment(user, contentID, containerID, request.getParameter("text").toString());
                    }

                    if (db3.containerIsViewableByUser(containerID, user)) {
                        int[] comments = db.getCommentsOnContent(contentID);
                        if (comments.length > 0) {
                            for (int i = 0; i < comments.length; ++i) {
                                output += getHTMLCommentOnContent(comments[i]);
                            }
                            out.print(output);
                        } else {
                            out.print("<div class=\"comment\" style=\"padding:8px; border: 1px dashed; border-color:#800000; text-align:center;\">No comments.</div>");
                        }
                    } else {
                        out.print("<div class=\"comment\" style=\"padding:8px; border: 1px dashed; border-color:#800000; text-align:center;\">No comments.</div>");
                    }
                } else {
                    if (request.getParameter("text") != null && request.getParameter("commentidchange") != null && request.getParameter("containerid") != null) {
                        changeComment(user, Integer.parseInt(request.getParameter("commentidchange")), contentID, containerID, request.getParameter("text").toString());
                    }

                    if (request.getParameter("commentiddelete") != null && request.getParameter("containerid") != null && request.getParameter("del") != null) {
                        deleteComment(user, Integer.parseInt(request.getParameter("commentiddelete")), Integer.parseInt(request.getParameter("contentid")), Integer.parseInt(request.getParameter("containerid")));
                    }

                    if (request.getParameter("containerid") != null && request.getParameter("text") != null && request.getParameter("add") != null) {
                        addCommentOnComment(user, Integer.parseInt(request.getParameter("commentid")), Integer.parseInt(request.getParameter("containerid")), request.getParameter("text").toString());
                    }

                    if (db3.containerIsViewableByUser(containerID, user)) {
                        int[] comments = db.getCommentsOnComment(commentID);
                        if (comments.length > 0) {
                            for (int i = 0; i < comments.length; ++i) {
                                output += getHTMLCommentOnComment(comments[i]);
                            }
                            out.print(output);
                        } else {
                            out.print("<div class=\"comment\" style=\"background-color:#FF9966;margin:25px;margin-bottom:2px; margin-top:2px;border: 1px dotted; border-color:#C0C0C0; text-align:center;\">No comments.</div>");
                        }
                    } else {
                        out.print("<div class=\"comment\" style=\"background-color:#FF9966;margin:25px;margin-bottom:2px; margin-top:2px;border: 1px dotted; border-color:#C0C0C0; text-align:center;\">No comments.</div>");
                    }
                }
            }
        } finally {
            if (db3.containerIsViewableByUser(containerID, user) && request.getParameter("content") != null) {
                if (loggedIn) {
                    out.print("<div class=\"comment\" style=\"padding:8px; border: 1px dashed; border-color:#800000; text-align:center;\"><form action=\"\" method=\"post\"><table style=\"width:100%; text-align:center;\"><tr><td><textarea id=\"newcommentfor" + contentID + "\" rows=\"8\" cols=\"65\" style=\"text-align:left;\" onclick=\"if(this.value.match(/^Please enter/) == 'Please enter')this.value='';\">Please enter your message here.\nPress \"Add message\" afterwards.</textarea></td></tr>" +
                            "<tr><td style=\"text-align:center;\"><input type=\"button\" onclick=\"addComment(" + contentID + ", " + containerID + ", document.getElementById('newcommentfor" + contentID + "').value);\" value=\"Add message\" /></td></tr></table></form></div>");
                } else {
                    out.print("<div class=\"comment\" style=\"padding:8px; border: 1px dashed; border-color:#800000; text-align:center;\">You need to log in before you can write messages.</div>");
                }
            } else if (db3.containerIsViewableByUser(containerID, user)) {
                if (loggedIn) {
                    out.print("<div class=\"comment\" style=\"background-color:#FF9966;margin:25px;margin-bottom:2px; margin-top:2px;border: 1px dotted; border-color:#C0C0C0; text-align:center;\"><div><form action=\"\" method=\"post\"><table style=\"width:100%; text-align:center;\"><tr><td><textarea id=\"newcommentforcomment" + commentID + "\" rows=\"4\" cols=\"45\" style=\"text-align:left;\" onclick=\"if(this.value.match(/^Please enter/) == 'Please enter')this.value='';\">Please enter your message here.\nPress \"Add message\" afterwards.</textarea></td></tr>" +
                            "<tr><td style=\"text-align:center;\"><input type=\"button\" onclick=\"addCommentOnComment(" + contentID + ", " + commentID + ", " + containerID + ", document.getElementById('newcommentforcomment" + commentID + "').value);\" value=\"Add message\" /></td></tr></table></form></div></div>");
                } else {
                    out.print("<div class=\"comment\" style=\"background-color:#FF9966;margin:25px;margin-bottom:2px; margin-top:2px;border: 1px dotted; border-color:#C0C0C0; text-align:center;\">You need to log in before you can write messages.</div>");
                }
            }

            out.close();
        }
    }

    private void changeComment(String user, int comment, int content, int container, String text) {
        if (db.isWrittenBy(user, comment) || ownerOfContainer) {
            db.changeComment(comment, text);
        }
    }

    private void deleteComment(String user, int comment, int content, int container) {
        if (ownerOfContainer) {
            db.removeComment(comment);
        }
    }

    private void addComment(String user, int content, int container, String text) {
        if (db3.containerIsViewableByUser(container, user)) {
            db.addCommentToContent(user, text, content);
        }
    }

    private void addCommentOnComment(String user, int comment, int container, String text) {
        if (db3.containerIsViewableByUser(container, user)) {
            db.addCommentToComment(user, text, comment);
        }
    }

    private String getHTMLCommentOnContent(int commentID) {
        boolean writer = db.isWrittenBy(user, commentID);
        CommentObject obj = db.getComment(commentID);
        obj.postedOn = obj.postedOn.substring(0, obj.postedOn.indexOf('.'));

        String result = "";
        if (ownerOfContainer) {
            result = "<div class=\"comment\" style=\"padding:8px; border: 1px dashed; border-color:#800000; text-align:center;\"><div><form action=\"\" method=\"post\"><table style=\"width:100%; text-align:center;\"><tr><td colspan=\"2\" style=\"text-align:left;\">Posted by <a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + obj.author + "\">" + obj.author + "</a>, on " + obj.postedOn +
                    ":</td></tr><tr><td colspan=\"2\"><textarea id=\"comment" + commentID + "\" rows=\"8\" cols=\"65\" style=\"text-align:left;\">" + obj.text + "</textarea></td></tr>" +
                    "<tr><td style=\"text-align:center;\"><input type=\"button\" onclick=\"changeComment(" + obj.contentID + ", " + commentID + ", " + containerID + ", document.getElementById('comment" + commentID + "').value);\" value=\"Edit this message\" />&nbsp;<input type=\"button\" onclick=\"deleteComment(" + obj.contentID + ", " + commentID + ", " + containerID + ");\" value=\"Remove this message\" /><br /></td><td style=\"text-align:center;\">&nbsp;" +
                    "Comments: <span class=\"anice\" onclick=\"showCommentsOnComment(" + commentID + ", " + contentID + ");\">show</span>/<span class=\"anice\" onclick=\"hideCommentsOnComment(" + commentID + ", " + contentID + ");\">hide</span></td></tr><tr><td colspan=\"2\" style=\"padding: 10px; padding-bottom:2px; padding-top:2px; text-align:center;\"><div class=\"comments\" id=\"commentscomment" + commentID + "\"></div></td></tr>" +
                    "</table></form></div></div>";
        } else if (writer) {
            result = "<div class=\"comment\" style=\"padding:8px; border: 1px dashed; border-color:#800000;text-align:center;\"><div><form action=\"\" method=\"post\"><table style=\"width:100%; text-align:center;\"><tr><td colspan=\"2\" style=\"text-align:left;\">Posted by <a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + obj.author + "\">" + obj.author + "</a>, on " + obj.postedOn +
                    ":</td></tr><tr><td colspan=\"2\"><textarea id=\"comment" + commentID + "\" rows=\"8\" cols=\"65\" style=\"text-align:left;\">" + obj.text + "</textarea></td></tr>" +
                    "<tr><td style=\"text-align:center;\"><input type=\"button\" onclick=\"changeComment(" + obj.contentID + ", " + commentID + ", " + containerID + ", document.getElementById('comment" + commentID + "').value);\" value=\"Edit your message\" /><br /></td><td style=\"text-align:center;\">&nbsp;" +
                    "Comments: <span class=\"anice\" onclick=\"showCommentsOnComment(" + commentID + ", " + contentID + ");\">show</span>/<span class=\"anice\" onclick=\"hideCommentsOnComment(" + commentID + ", " + contentID + ");\">hide</span></td></tr><tr><td colspan=\"2\" style=\"padding: 10px; padding-bottom:2px; padding-top:2px;  text-align:center;\"><div class=\"comments\" id=\"commentscomment" + commentID + "\"></div></td></tr>" +
                    "</table></form></div></div>";
        } else {
            result = "<div class=\"comment\" style=\"padding:8px; border: 1px dashed; border-color:#800000;text-align:center;\"><div><table style=\"width:100%; text-align:center;\"><tr><td colspan=\"2\" style=\"text-align:left;\">Posted by <a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + obj.author + "\">" + obj.author + "</a>, on " + obj.postedOn +
                    ":</td></tr><tr><td colspan=\"2\"><textarea readonly=\"readonly\" rows=\"8\" cols=\"65\" style=\"text-align:left;\">" + obj.text + "</textarea></td></tr>" +
                    "<tr><td style=\"text-align:center;\" colspan=\"2\">&nbsp;Comments: <span class=\"anice\" onclick=\"showCommentsOnComment(" + commentID + ", " + contentID + ");\">show</span>/<span class=\"anice\" onclick=\"hideCommentsOnComment(" + commentID + ", " + contentID + ");\">hide</span></td></tr><tr><td colspan=\"2\" style=\"padding: 10px; padding-bottom:2px; padding-top:2px; text-align:center;\"><div class=\"comments\" id=\"commentscomment" + commentID + "\"></div></td></tr>" +
                    "</table></div></div>";
        }

        return result;
    }

    private String getHTMLCommentOnComment(int commentID2) {
        boolean writer = db.isWrittenBy(user, commentID2);
        CommentObject obj = db.getComment(commentID);
        CommentObject obj2 = db.getComment(commentID2);
        obj.postedOn = obj.postedOn.substring(0, obj.postedOn.indexOf('.'));
        obj2.postedOn = obj2.postedOn.substring(0, obj2.postedOn.indexOf('.'));

        String result = "";
        if (ownerOfContainer) {
            result = "<div class=\"comment\" style=\"background-color:#FF9966;margin:25px;margin-bottom:2px; margin-top:2px;border: 1px dotted; border-color:#C0C0C0; text-align:center;\"><div><form action=\"\" method=\"post\"><table style=\"width:100%; text-align:center;\"><tr><td colspan=\"2\" style=\"text-align:left;\">Posted by <a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + obj2.author + "\">" + obj2.author + "</a>, on " + obj2.postedOn +
                    ":</td></tr><tr><td colspan=\"2\" style=\"text-align:center;\"><textarea id=\"commentOnComment" + commentID2 + "\" rows=\"4\" cols=\"45\" style=\"text-align:left;\">" + obj2.text + "</textarea></td></tr>" +
                    "<tr><td style=\"text-align:center;\"><input type=\"button\" onclick=\"changeCommentOnComment(" + obj.contentID + ", " + commentID + ", " + commentID2 + ", " + containerID + ", document.getElementById('commentOnComment" + commentID2 + "').value);\" value=\"Edit this message\" />&nbsp;<input type=\"button\" onclick=\"deleteCommentOnComment(" + obj.contentID + ", " + commentID + ", " + commentID2 + ", " + containerID + ");\" value=\"Remove this message\" /></td>" +
                    "</tr></table></form></div></div>";
        } else if (writer) {
            result = "<div class=\"comment\" style=\"background-color:#FF9966;margin:25px;margin-bottom:2px; margin-top:2px;border: 1px dotted; border-color:#C0C0C0; text-align:center;\"><div><form action=\"\" method=\"post\"><table style=\"width:100%; text-align:center;\"><tr><td colspan=\"2\" style=\"text-align:leftt;\">Posted by <a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + obj2.author + "\">" + obj2.author + "</a>, on " + obj2.postedOn +
                    "</td></tr><tr><td colspan=\"2\" style=\"text-align:center;\"><textarea id=\"commentOnComment" + commentID2 + "\" rows=\"4\" cols=\"45\" style=\"text-align:left;\">" + obj2.text + "</textarea></td></tr>" +
                    "<tr><td style=\"text-align:center;\"><input type=\"button\" onclick=\"changeCommentOnComment(" + obj.contentID + ", " + commentID + ", " + commentID2 + ", " + containerID + ", document.getElementById('commentOnComment" + commentID2 + "').value);\" value=\"Edit this message\" /></td>" +
                    "</tr></table></form></div></div>";
        } else {
            result = "<div class=\"comment\" style=\"background-color:#FF9966;margin:25px;margin-bottom:2px; margin-top:2px;border: 1px dotted; border-color:#C0C0C0; text-align:center;\"><div><table style=\"width:100%; text-align:center;\"><tr><td colspan=\"2\" style=\"text-align:left;\">Posted by <a class=\"nice\"  href=\"index.jsp?page=profile&amp;user=" + obj2.author + "\">" + obj2.author + "</a>, on " + obj2.postedOn +
                    "</td></tr><tr><td colspan=\"2\" style=\"text-align:center;\"><textarea readonly=\"readonly\" rows=\"4\" cols=\"45\" style=\"text-align:left;\">" + obj2.text + "</textarea></td></tr></table></div></div>";
        }

        return result;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
